package com.zbu.reggie.common;


import com.alibaba.fastjson.JSONObject;
import com.zbu.reggie.entity.OperateLog;
import com.zbu.reggie.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@Aspect//切面类 需要引入AOP的依赖
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.zbu.reggie.config.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 从Session中获取用户ID（键名为"employee"）
        Long operateUser = (Long) request.getSession().getAttribute("employee");

        // 获取被拦截方法的签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        // 获取方法名
        String methodName = method.getName();

        // 获取类名
        String className = method.getDeclaringClass().getName();

        // 获取方法参数
//        Object[] args = joinPoint.getArgs();
//        String methodParams = JSONObject.toJSONString(args);

        // 过滤特殊类型参数
        Object[] args = joinPoint.getArgs();
        List<Object> filteredArgs = Arrays.stream(args)
                .filter(arg -> !(arg instanceof HttpServletResponse) && !(arg instanceof MultipartFile))
                .collect(Collectors.toList());
        String methodParams = JSONObject.toJSONString(filteredArgs);


        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 执行方法
        Object result = joinPoint.proceed();

        // 记录结束时间
        long endTime = System.currentTimeMillis();

        // 计算执行耗时
        long costTime = endTime - startTime;

        // 获取返回值
        String returnValue = JSONObject.toJSONString(result);


        // 创建日志对象
        OperateLog operateLog = new OperateLog(
                null, // ID 由数据库自动生成
                operateUser,
                LocalDateTime.now(),
                className,
                methodName,
                methodParams,
                returnValue,
                costTime
        );

        // 插入日志到数据库
        operateLogMapper.insert(operateLog);
        // 记录日志到控制台
        log.info("AOP中记录操作日志：{}", operateLog);
        return result;

    }
}
